package com.utils;

import java.io.File;
import java.util.ArrayList;
import javax.swing.filechooser.FileFilter;

/**
 * 17 Feb 2009
 * @author Sajarwo
 */
public class MapFileFilter extends FileFilter {

    private String description = "File GIF & PNG";
    private ArrayList filterExtension;
    /**
     *
     * @param auto diset true akan memberi nilai default extensi GIF & PNG
     */
    public MapFileFilter(boolean auto) {
        filterExtension = new ArrayList<String>();
        if (auto) {
            addFilterExtension("gif");
            addFilterExtension("png");
        }
    }

    /**
     * 
     * @param filterExtension array untuk definisi extensi file
     * @param description deskripsi
     */
    public MapFileFilter(String filterExtension,String description) {
        this.filterExtension = new ArrayList<String>();
        addFilterExtension(filterExtension);
        setDescription(description);
    }

    
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }
        String extension = getExtension(f);
        if (extension != null) {
            for (int i = 0; i < filterExtension.size(); i++) {
                if (extension.equals(filterExtension.get(i))) {
                    return true;
                }
            }
        }
        return false;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void addFilterExtension(String filterExtension) {
        this.filterExtension.add(filterExtension);
    }

    public void addFilterExtension(String filterExtension[]) {
        for (int i = 0; i < filterExtension.length; i++) {
            addFilterExtension(filterExtension[i]);
        }
    }

    public void removeFilterExtension(String filterExtension) {
        this.filterExtension.remove(filterExtension);
    }

    public void removeFilterExtensionAll() {
        this.filterExtension.clear();
    }

    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');
        if (i > 0 && i < s.length() - 1) {
            ext = s.substring(i + 1).toLowerCase();
        }
        return ext;
    }

    public static String getPrefix(String fnm) // extract name before '.' of filename
    {
        int posn;
        if ((posn = fnm.lastIndexOf(".")) == -1) {
            System.out.println("No prefix found for filename: " + fnm);
            return fnm;
        } else {
            return fnm.substring(0, posn);
        }
    } // end of getPrefix()

    
}
